/*
 * name: lazyload.js
 * version: v1.0.2
 * update: 修复事件解绑bug;快速滚动src获取错误bug;
 * date: 2014-11-06
 */
define(function(require, exports, module) {
	var $ = require('jquery');
	require('img-loaded');
	$.fn.lazyload = function(config) {
		var lazyload,lock = false,
			opt = {
				showSpeed: 256,			// 显示速度
				firstCount: 1,			// 初始加载
				everyCount: 1,			// 每次加载
				distance: 100			// 进入视野距离
			},
			$this = $(this),
			lazyimgs = $this.is($(window)) ? $('img[data-lazy]') : $this.find('img[data-lazy]');
		if(!lazyimgs.length) return false;
		$.extend( opt, config || {});
		//初始加载	
		for (i = 0; i < opt.firstCount; i++) {
			if(i>lazyimgs.length) return;
			lazyimgs.eq(i).attr("src", lazyimgs.eq(i).data('lazy')).data('lazy', 'finish');
		};
		lazyload = function () {
			lazyimgs = lazyimgs.filter(function(){
				if($(this).data('lazy') !='finish'){
					return this;
				}
			});		
			if (!lazyimgs.length) {
				$this.unbind({
					'scroll':lazyload,
					'resize':lazyload
				});
				return true;
			};
			$this.imagesLoaded(function(){
				if (lazyimgs.eq(0).offset().top < ($this.height() + $this.scrollTop() + opt.distance)) {
					for (i = 0; i < opt.everyCount; i++) {
						if(i>lazyimgs.length) return;
						var _dataLazy = lazyimgs.eq(i).data('lazy');
						if(_dataLazy!='finish'){
							lazyimgs.eq(i).hide().
							attr("src", _dataLazy).
							data('lazy', 'finish').
							fadeIn(opt.showSpeed);
						}
					}
				};
			});
		};
		lazyload();
		$this.bind({
			'scroll':lazyload,
			'resize':lazyload
		});
		return $this;
	};
})